// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 移动菜单功能
    const menuToggle = document.querySelector('.menu-toggle');
    const mobileMenu = document.querySelector('.mobile-menu');
    const mobileMenuLinks = mobileMenu.querySelectorAll('.mobile-menu__link');
    const body = document.body;

    // 移动菜单切换
    menuToggle.addEventListener('click', function() {
        mobileMenu.classList.toggle('active');
        menuToggle.classList.toggle('active');
    });

    // 点击移动菜单链接后关闭菜单
    mobileMenuLinks.forEach(link => {
        link.addEventListener('click', function() {
            mobileMenu.classList.remove('active');
            menuToggle.classList.remove('active');
        });
    });

    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                const headerHeight = document.querySelector('.header').offsetHeight;
                const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - headerHeight;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth',
                    duration: 800 // 添加滚动持续时间
                });
            }
        });
    });

    // 定价方案切换
    const pricingToggle = document.querySelector('.pricing__toggle-input');
    const pricingPeriods = document.querySelectorAll('.pricing-card__period');
    const pricingNumbers = document.querySelectorAll('.pricing-card__number');
    const pricingLabels = document.querySelectorAll('.pricing__toggle-label');
    
    if (pricingToggle) {
        pricingToggle.addEventListener('change', function() {
            const isAnnual = this.checked;
            
            // 更新标签状态
            pricingLabels.forEach((label, index) => {
                if (isAnnual && index === 1) {
                    label.classList.add('active');
                } else if (!isAnnual && index === 0) {
                    label.classList.add('active');
                } else {
                    label.classList.remove('active');
                }
            });
            
            // 更新价格标签
            pricingPeriods.forEach(period => {
                period.textContent = isAnnual ? '/年' : '/月';
            });
            
            // 更新价格数字（年付价格为月付的10倍，但显示优惠）
            const priceMultiplier = isAnnual ? 8 : 1; // 年付8折优惠
            const basePrices = [999, 2999, 9999]; // 基础价格
            
            pricingNumbers.forEach((number, index) => {
                const originalPrice = basePrices[index];
                const newPrice = Math.round(originalPrice * priceMultiplier);
                number.textContent = newPrice.toLocaleString();
            });
        });
        
        // 初始化标签状态
        pricingLabels[0].classList.add('active');
    }

    // 定价卡片选中效果 - 单选模式
    const pricingCards = document.querySelectorAll('.pricing-card');
    let selectedCard = null;
    
    pricingCards.forEach(card => {
        card.addEventListener('click', function() {
            // 如果点击的是已选中的卡片，则取消选中
            if (this.classList.contains('selected')) {
                this.classList.remove('selected');
                selectedCard = null;
                updateAriaAttributes();
                return;
            }
            
            // 移除其他卡片的选中状态
            pricingCards.forEach(c => {
                c.classList.remove('selected');
            });
            
            // 添加当前卡片的选中状态
            this.classList.add('selected');
            selectedCard = this;
            
            // 更新可访问性属性
            updateAriaAttributes();
            
            // 添加选中动画效果
            this.style.transform = 'scale(1.02)';
            setTimeout(() => {
                this.style.transform = '';
            }, 200);
        });
        
        // 添加键盘支持
        card.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.click();
            }
        });
        
        // 设置可访问性属性
        card.setAttribute('tabindex', '0');
        card.setAttribute('role', 'radio');
        card.setAttribute('aria-checked', 'false');
    });
    
    // 更新选中状态的可访问性属性
    function updateAriaAttributes() {
        pricingCards.forEach(card => {
            const isSelected = card.classList.contains('selected');
            card.setAttribute('aria-checked', isSelected.toString());
        });
        
        // 调试信息
        const selectedCards = document.querySelectorAll('.pricing-card.selected');
        console.log('当前选中的卡片数量:', selectedCards.length);
        selectedCards.forEach((card, index) => {
            console.log(`选中卡片 ${index + 1}:`, card.querySelector('.pricing-card__title')?.textContent);
        });
    }
    
    // 初始化：默认选中"成长方案"（最受欢迎）
    function initializePricingSelection() {
        const popularCard = document.querySelector('.pricing-card--popular');
        if (popularCard) {
            // 确保所有卡片初始状态正确
            pricingCards.forEach(card => {
                card.classList.remove('selected');
            });
            
            // 选中成长方案
            popularCard.classList.add('selected');
            selectedCard = popularCard;
            updateAriaAttributes();
            
            console.log('✅ 默认选中成长方案成功！');
            console.log('成长方案选中状态:', popularCard.classList.contains('selected'));
            console.log('边框颜色应该是绿色:', getComputedStyle(popularCard).borderColor);
        }
    }
    
    // 初始化定价选择 - 确保DOM完全加载
    function initPricing() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializePricingSelection);
        } else {
            initializePricingSelection();
        }
    }
    
    // 执行初始化
    initPricing();
    
    // 添加调试功能 - 在控制台可以手动调用
    window.debugPricing = {
        init: initializePricingSelection,
        getSelected: () => document.querySelectorAll('.pricing-card.selected'),
        selectCard: (index) => {
            const cards = document.querySelectorAll('.pricing-card');
            if (cards[index]) {
                cards.forEach(c => c.classList.remove('selected'));
                cards[index].classList.add('selected');
                updateAriaAttributes();
            }
        },
        togglePopular: () => {
            const popularCard = document.querySelector('.pricing-card--popular');
            if (popularCard) {
                popularCard.classList.toggle('selected');
                updateAriaAttributes();
                console.log('成长方案选中状态:', popularCard.classList.contains('selected'));
            }
        }
    };
    
    console.log('定价调试工具已加载，可以使用 window.debugPricing 进行调试');

    // 按钮选中效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            // 如果是定价卡片内的按钮，不处理选中效果
            if (this.closest('.pricing-card')) {
                return;
            }
            
            // 移除同组其他按钮的选中状态
            const buttonGroup = this.closest('.btn-group');
            if (buttonGroup) {
                buttonGroup.querySelectorAll('.btn').forEach(btn => {
                    btn.classList.remove('selected');
                });
            }
            
            // 添加当前按钮的选中状态
            this.classList.add('selected');
        });
    });

    // 客户评价轮播 - 现代版
    const testimonialSlides = document.querySelectorAll('.testimonial-slide');
    const testimonialIndicators = document.querySelectorAll('.testimonial-indicator');
    let currentTestimonial = 0;
    let testimonialInterval;
    
    // 初始化轮播
    function initTestimonialSlider() {
        if (testimonialSlides.length <= 1) return;
        
        // 初始设置所有幻灯片隐藏，第一张显示
        testimonialSlides.forEach((slide, index) => {
            slide.style.display = index === 0 ? 'block' : 'none';
        });
        
        // 自动轮播
        startTestimonialInterval();
        
        // 添加指示器点击事件
        testimonialIndicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                goToTestimonial(index);
                restartTestimonialInterval();
            });
        });
    }
    
    // 跳转到指定评价
    function goToTestimonial(index) {
        // 隐藏所有幻灯片
        testimonialSlides.forEach(slide => {
            slide.style.display = 'none';
        });
        
        // 重置所有指示器
        testimonialIndicators.forEach(indicator => {
            indicator.classList.remove('testimonial-indicator--active');
        });
        
        // 设置新的当前索引
        currentTestimonial = index;
        
        // 显示当前幻灯片
        testimonialSlides[currentTestimonial].style.display = 'block';
        
        // 激活当前指示器
        testimonialIndicators[currentTestimonial].classList.add('testimonial-indicator--active');
    }
    
    // 下一个评价
    function nextTestimonial() {
        const nextIndex = (currentTestimonial + 1) % testimonialSlides.length;
        goToTestimonial(nextIndex);
    }
    
    // 启动轮播定时器
    function startTestimonialInterval() {
        testimonialInterval = setInterval(nextTestimonial, 6000); // 6秒切换一次
    }
    
    // 重启轮播定时器
    function restartTestimonialInterval() {
        clearInterval(testimonialInterval);
        startTestimonialInterval();
    }
    
    // 初始化评价轮播
    initTestimonialSlider();

    // 滚动动画效果 - 现代化实现
    const animateOnScroll = () => {
        const elements = document.querySelectorAll('.animate-fade-in, .animate-scale-in');
        
        elements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const windowHeight = window.innerHeight;
            const triggerPoint = windowHeight * 0.85; // 触发点：当元素底部进入视口85%时
            
            if (elementPosition < triggerPoint && !element.classList.contains('active')) {
                element.classList.add('active');
            }
        });
    };
    
    // 页面加载时立即显示关键内容区域
    document.querySelectorAll('.animate-fade-in, .animate-scale-in').forEach(element => {
        // 立即显示首屏内容
        if (element.getBoundingClientRect().top < window.innerHeight * 1.5) {
            element.classList.add('active');
        }
    });
    
    // 初始化滚动动画
    animateOnScroll();
    window.addEventListener('scroll', animateOnScroll);

    // 导航栏滚动效果
    const header = document.querySelector('.header');
    
    function handleNavScroll() {
        if (window.scrollY > 50) {
            header.classList.add('header--scrolled');
        } else {
            header.classList.remove('header--scrolled');
        }
    }
    
    window.addEventListener('scroll', handleNavScroll);
    handleNavScroll(); // 初始化导航栏状态

    // 表单验证 - 现代化实现
    const demoForm = document.querySelector('.demo-form');
    
    if (demoForm) {
        demoForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            let isValid = true;
            const formInputs = this.querySelectorAll('.demo-form__input');
            
            // 重置所有输入框的错误状态
            formInputs.forEach(input => {
                input.classList.remove('demo-form__input--error');
            });
            
            // 验证每个输入框
            formInputs.forEach(input => {
                if (!input.value.trim()) {
                    isValid = false;
                    input.classList.add('demo-form__input--error');
                    input.setAttribute('aria-invalid', 'true');
                } else {
                    input.setAttribute('aria-invalid', 'false');
                }
            });
            
            // 验证手机号码格式
            const phoneInput = this.querySelector('.demo-form__input[type="tel"]');
            if (phoneInput) {
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!phoneRegex.test(phoneInput.value.trim())) {
                    isValid = false;
                    phoneInput.classList.add('demo-form__input--error');
                    phoneInput.setAttribute('aria-invalid', 'true');
                }
            }
            
            if (isValid) {
                // 模拟表单提交动画
                const submitBtn = this.querySelector('.demo-form__submit');
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 提交中...';
                
                // 模拟API请求延迟
                setTimeout(() => {
                    // 显示成功消息
                    const formWrapper = this.closest('.cta__form');
                    const successMessage = document.createElement('div');
                    successMessage.className = 'success-message';
                    successMessage.innerHTML = `
                        <div class="success-message__icon">
                            <i class="fa fa-check-circle"></i>
                        </div>
                        <h3 class="success-message__title">预约成功！</h3>
                        <p class="success-message__desc">我们的专业顾问将在1-2个工作日内与您联系，为您提供详细的产品演示。</p>
                    `;
                    
                    // 隐藏表单，显示成功消息
                    formWrapper.innerHTML = '';
                    formWrapper.appendChild(successMessage);
                    
                    // 重置表单
                    this.reset();
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '立即预约演示';
                }, 1500);
            }
        });
        
        // 输入框焦点事件 - 移除错误状态
        const formInputs = demoForm.querySelectorAll('.demo-form__input');
        formInputs.forEach(input => {
            input.addEventListener('focus', function() {
                this.classList.remove('demo-form__input--error');
            });
            
            // 实时验证
            input.addEventListener('input', function() {
                if (this.value.trim()) {
                    this.classList.remove('demo-form__input--error');
                    this.setAttribute('aria-invalid', 'false');
                }
            });
        });
    }

    // 平滑滚动到顶部按钮
    const scrollToTopBtn = document.createElement('button');
    scrollToTopBtn.innerHTML = '<i class="fa fa-chevron-up"></i>';
    scrollToTopBtn.className = 'scroll-top';
    scrollToTopBtn.setAttribute('aria-label', '回到顶部');
    document.body.appendChild(scrollToTopBtn);
    
    // 返回顶部按钮点击事件
    scrollToTopBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth',
            duration: 800
        });
    });
    
    // 监听滚动显示/隐藏返回顶部按钮
    function toggleScrollToTopBtn() {
        if (window.scrollY > 500) {
            scrollToTopBtn.classList.add('visible');
        } else {
            scrollToTopBtn.classList.remove('visible');
        }
    }
    
    window.addEventListener('scroll', toggleScrollToTopBtn);
    toggleScrollToTopBtn(); // 初始化状态

    // 图片懒加载 - 使用IntersectionObserver
    if ('IntersectionObserver' in window && 'loading' in HTMLImageElement.prototype) {
        const lazyImages = document.querySelectorAll('img[loading="lazy"]');
        
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    
                    // 支持data-srcset
                    if (img.dataset.srcset) {
                        img.srcset = img.dataset.srcset;
                    }
                    
                    // 支持data-src
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                    }
                    
                    // 添加加载完成动画
                    img.onload = () => {
                        img.classList.add('img--loaded');
                    };
                    
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '200px 0px' // 预加载：提前200px开始加载
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    }

    // 添加页面加载动画
    window.addEventListener('load', function() {
        // 移除加载状态类
        body.classList.add('page--loaded');
        
        // 初始化英雄区域动画
        setTimeout(() => {
            const heroContent = document.querySelector('.hero__content');
            const heroVisual = document.querySelector('.hero__visual');
            
            if (heroContent) heroContent.classList.add('hero__content--visible');
            if (heroVisual) heroVisual.classList.add('hero__visual--visible');
        }, 200);
    });

    // 增强交互体验：悬停效果和微动画
    function enhanceInteractions() {
        // 解决方案卡片悬停效果
        const solutionCards = document.querySelectorAll('.solution-card');
        solutionCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-8px) scale(1.02)';
                this.style.boxShadow = '0 20px 40px rgba(0, 0, 0, 0.15)';
            });
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0) scale(1)';
                this.style.boxShadow = '';
            });
        });
        
        // 功能卡片悬停效果
        const featureCards = document.querySelectorAll('.feature-card');
        featureCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                const icon = this.querySelector('.feature-card__icon');
                if (icon) {
                    icon.style.transform = 'scale(1.1) rotate(5deg)';
                }
                this.style.transform = 'translateY(-5px)';
            });
            card.addEventListener('mouseleave', function() {
                const icon = this.querySelector('.feature-card__icon');
                if (icon) {
                    icon.style.transform = 'scale(1) rotate(0deg)';
                }
                this.style.transform = 'translateY(0)';
            });
        });
        
        // 行业卡片悬停效果
        const industryCards = document.querySelectorAll('.industry-card');
        industryCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                const overlay = this.querySelector('.industry-card__image-overlay');
                if (overlay) {
                    overlay.style.opacity = '0.8';
                }
                this.style.transform = 'translateY(-8px) scale(1.02)';
            });
            card.addEventListener('mouseleave', function() {
                const overlay = this.querySelector('.industry-card__image-overlay');
                if (overlay) {
                    overlay.style.opacity = '0.6';
                }
                this.style.transform = 'translateY(0) scale(1)';
            });
        });
        
        // 定价卡片悬停效果（已在CSS中处理，这里添加额外效果）
        const pricingCards = document.querySelectorAll('.pricing-card');
        pricingCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                if (!this.classList.contains('pricing-card--popular') && !this.classList.contains('selected')) {
                    this.classList.add('pricing-card--hover');
                }
            });
            card.addEventListener('mouseleave', function() {
                this.classList.remove('pricing-card--hover');
            });
        });

        // 按钮悬停效果增强
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(button => {
            button.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px) scale(1.05)';
            });
            button.addEventListener('mouseleave', function() {
                if (!this.classList.contains('selected')) {
                    this.style.transform = 'translateY(0) scale(1)';
                }
            });
        });

        // 导航链接悬停效果
        const navLinks = document.querySelectorAll('.nav-link, .mobile-menu__link');
        navLinks.forEach(link => {
            link.addEventListener('mouseenter', function() {
                this.style.color = '#4f46e5';
                this.style.transform = 'translateY(-1px)';
            });
            link.addEventListener('mouseleave', function() {
                this.style.color = '';
                this.style.transform = 'translateY(0)';
            });
        });
    }
    
    // 初始化交互增强
    enhanceInteractions();
    
    // FAQ 交互功能
    function initFAQ() {
        const faqQuestions = document.querySelectorAll('.faq__question');
        
        if (faqQuestions.length === 0) return;
        
        faqQuestions.forEach(question => {
            question.addEventListener('click', () => {
                // 切换展开状态
                const isExpanded = question.getAttribute('aria-expanded') === 'true';
                question.setAttribute('aria-expanded', !isExpanded);
                
                // 查找对应的答案元素
                const answer = question.nextElementSibling;
                
                // 查找图标元素
                const icon = question.querySelector('.faq__icon');
                
                // 设置初始样式以启用动画
                answer.style.maxHeight = answer.style.maxHeight || '0';
                answer.style.opacity = answer.style.opacity || '0';
                answer.style.transition = 'max-height 0.3s ease, opacity 0.3s ease';
                answer.style.overflow = 'hidden';
                answer.classList.remove('hidden');
                
                // 切换显示/隐藏
                if (!isExpanded) {
                    // 展开动画
                    answer.style.maxHeight = answer.scrollHeight + 'px';
                    answer.style.opacity = '1';
                    
                    // 旋转图标
                    icon.style.transform = 'rotate(180deg)';
                } else {
                    // 收起动画
                    answer.style.maxHeight = '0';
                    answer.style.opacity = '0';
                }
            });
        });
    }
    
    // 初始化FAQ功能
    initFAQ();
    
    // 响应式处理 - 根据视口大小调整交互
    function handleResponsive() {
        const isMobile = window.innerWidth < 768;
        
        // 根据设备类型调整动画和交互
        if (isMobile) {
            // 移动设备优化
            const heroContent = document.querySelector('.hero__content');
            if (heroContent) {
                heroContent.style.animationDuration = '0.8s';
            }
        }
    }
    
    // 初始化响应式处理
    handleResponsive();
    window.addEventListener('resize', handleResponsive);
});